const { defineConfig } = require("@vue/cli-service");
const { VantResolver } = require("@vant/auto-import-resolver");
const ComponentsPlugin = require("unplugin-vue-components/webpack");
const bodyParser = require('body-parser');
const Mock = require("mockjs");
const data = Mock.mock({
  "list|100": [
    {
      "id": "@id",
      "title": "@ctitle",
      "desc": "@cword(10, 20)",
      "image": "@image(150x180, @color, item)",
      "price|10-100": 1,
      "message|3-5": [{
        "id": "@id",
        "avator": "@image(20x20, @color)",
        "nickname": "@cname",
        "content": "@cword(10, 20)",
        "datetime": "@datetime",
      }]
    },
  ],
  userList: [{
    "username": 'zhangsan',
    "password": 'zhangsan',
    "nickname": '阿三',
    "avator": "@image(20x20, @color)",
  },{
    "username": 'lisi',
    "password": 'lisi',
    "nickname": '四大天王',
    "avator": "@image(20x20, @color)",
  }]
});

module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    setupMiddlewares(middlewares, devServer) {
      devServer.app.use(bodyParser.json())
      // 后端支持分页  
      // 参数： pageCode 页码   pageSize 每页个数
      // 请求方式 get
      devServer.app.get("/list", (req, res) => {
        // 设置默认值 
        const { pageCode = 1, pageSize = 10} = req.query;
        // 分页公式
        // 数据.slice((页码 - 1) * 每页个数， 页码 * 每页个数)
        const sliceData = data.list.slice((pageCode - 1) * pageSize, pageCode * pageSize);
        // 测试通过
        res.send(sliceData);
      });

      // 详情接口
      devServer.app.get('/list/detail', (req, res) => {
        const { id } = req.query;
        const item = data.list.find(v => v.id === id)
        res.send(item)
      })

      // 登录接口
      devServer.app.post('/login', (req, res) => {
        const { username, password } = req.body;
        const user = data.userList.find(v => v.username === username && v.password === password);
        if(user) {
          res.send({
            code: 200,
            message: '登录成功， 换欢迎' + user.nickname,
            data: {
              userInfo: user,
              token: 'qowlemqpw;emqpw;eqweq'
            }
          })
        } else {
          res.send({
            code: 400,
            message: '账户密码错误， 请重新登录'
          })
        }
      })
      return middlewares;
    },
  },
  configureWebpack: {
    plugins: [
      ComponentsPlugin.default({ resolvers: [VantResolver()] }), //当 unplugin-vue-components 版本大于等于 0.26.0
    ],
  },
});
